package com.idea.zd.sys.design.single;


class Single{
    private static Single single;

    private Single(){

    }

    //线程不安全加上synchronized就线程安全
    public static Single getInstance(){
        System.out.println(Thread.currentThread().getName());
        if(single == null){
            System.out.println("没有实例");
            single = new Single();
        }else{
            System.out.println("已存在实例");
        }
        System.out.println(single);
        return single;
    }
}

class Threads implements Runnable{

    @Override
    public void run() {
        Single.getInstance();
    }
}

/**
 * 饿汉式 初试化静态的instance创建一次。如果我们在Singleton类里面写一个静态的方法不需要创建实例，它仍然会早早的创建一次实例。而降低内存的使用率。
 */
class Singleton {
    private static Singleton instance=new Singleton();
    private Singleton(){
        System.out.println("创建");
    }
    public static Singleton getInstance(){
        return instance;
    }
}

/**
 * 静态内部类创建
 */
class Singletons {
    private Singletons(){
        System.out.println("创建");
    }
    private static class SingletonHolder{
        private final static Singletons instance=new Singletons();
    }
    public static Singletons getInstance(){
        return SingletonHolder.instance;
    }
}


public class singleTest {

    public static void main(String [] args){
        /*Single.getInstance();*/

        new Thread(new Threads(),"线程1").start();
        new Thread(new Threads(),"线程2").start();
        new Thread(new Threads(),"线程3").start();
        new Thread(new Threads(),"线程4").start();
        new Thread(new Threads(),"线程5").start();
        new Thread(new Threads(),"线程6").start();
        new Thread(new Threads(),"线程7").start();
        new Thread(new Threads(),"线程8").start();
        new Thread(new Threads(),"线程9").start();
        new Thread(new Threads(),"线程10").start();
        new Thread(new Threads(),"线程11").start();
        new Thread(new Threads(),"线程12").start();
        new Thread(new Threads(),"线程13").start();
        new Thread(new Threads(),"线程14").start();
        new Thread(new Threads(),"线程15").start();
        new Thread(new Threads(),"线程16").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Single.getInstance();
            }
        },"线程2").start();

        /*Singletons.getInstance();

        Singletons.getInstance();*/


    }
}
